var websocket = null;

/**
 * 初始化WebSocket
 * */
function initWebSocket() {
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        var url = 'ws://' + $(location).attr('host') + ctxPath + '/admin/websocket/log/infos';
        websocket = new WebSocket(url);
    } else {
        alert('Not support WebSocket');
    }

//连接成功建立的回调方法
    websocket.onopen = function (event) {
        console.log('Info: connection opened.');
    };

//连接发生错误的回调方法
    websocket.onerror = function () {
        console.log('onError:');
    };

//接收到消息的回调方法
    websocket.onmessage = function (event) {
        // console.log(event.data);
        logInfo(event.data);
    };

//连接关闭的回调方法
    websocket.onclose = function () {
        console.log('Info: connection closed.');
        closeWebSocket();
    };

//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeUnload = function () {
        websocket.close();
    };
}

//关闭连接
function closeWebSocket() {
    if (websocket != null) {
        websocket.close();
        websocket = null;
    }
}

//发送消息
function sendMessage(message) {
    if (websocket != null) {
        websocket.send(JSON.stringify(message));
    }
}

//显示日志信息
function logInfo(msg1) {
    var msg = '';
    try {
        msg = $.parseJSON(msg1);
        // console.log(msg);
    } catch (e) {
        alert('----' + msg1);
        return;
    }
    var html = "";
    switch (msg.level.levelStr) {
        case "INFO":
            // console.log("info!!!!!!!!!!!");
            html = '<div class="log bs-callout bs-callout-info bg-info text-info">'
                + msg.date + " " + msg.level.levelStr + " " + msg.logger + " " + msg.thread + " " + msg.message + " " + msg.exceptionMessage + "</div>"
            break;
        case "WARN":
            // console.log("warn!!!!!!!!!!!");
            html = '<div class="log bs-callout-danger bg-danger text-danger">'
                + msg.date + " " + msg.level.levelStr + " " + msg.logger + " " + msg.thread + " " + msg.message + " " + msg.exceptionMessage + "</div>"
            break;
        case "ERROR":
            // console.log("error!!!!!!!!!!!");
            html = '<div class="log bs-callout-danger bg-danger text-danger">'
                + msg.date + " " + msg.level.levelStr + " " + msg.logger + " " + msg.thread + " " + msg.message + " " + msg.exceptionMessage + "</div>"
            break;
        default:
            html = '<div class="log bs-callout bs-callout-info bg-info text-info">'
                + msg.date + " " + msg.level.levelStr + " " + msg.logger + " " + msg.thread + " " + msg.message + " " + msg.exceptionMessage + "</div>"
            break;
    }

    $('#logContainer').append(html);
    var h = $(document).height() - $(window).height();
    $(document).scrollTop(h);
}

$(function () {

    //初始化WebSocket
    initWebSocket();

    //Submit按钮点击事件监听
    $('#btnSubmit').click(function () {
        sendMessage({
            keyWord: $('#keyWord').val(),
            userName: $('#userName').val()
        });
        $('#btnClean').click();
    });

//清理日志按钮点击事件监听
    $('#btnClean').click(function () {
        $('.log').remove();
    });

//开启监听WebSocket按钮点击事件监听
    $('#btnStart').click(function () {

        if (websocket == null) {
            initWebSocket();
        }
    });

//关闭监听WebSocket按钮点击事件监听
    $('#btnClose').click(function () {
        closeWebSocket();
    });

//监听日志等级按钮点击事件
    $('#logLevel').on('click', 'li', function () {
        var level = $(this).attr('data-value');
        sendMessage({level: level});
        $('#btnClean').click();
    });

//监听日志名称按钮点击事件
    $('#logName').on('click', 'li', function () {
        var logger = $(this).attr('data-value');
        sendMessage({logger: logger});
        $('#btnClean').click();
    });
});